<template>
  <div>
    <!-- 面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!--搜素和添加区域
         el-row el-col 栅格布局
         :gutter="20" 两个列之间间距
         :span="8" 列多宽
         -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="clearquery"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="changequery"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisiable = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!--用户列表区
      
      :data="userlist" 指定数据源
label="姓名"  指定当前列标题
width="180"  指定列宽度
 prop="username" 指定绑定的数据
       -->
      <el-table :data="userlist" border stripe>
        <!-- 索引列
          type="index"
          -->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" width="180" prop="username">
        </el-table-column>
        <el-table-column label="邮箱" width="180" prop="email">
        </el-table-column>
        <el-table-column label="电话" width="180" prop="mobile">
        </el-table-column>
        <el-table-column label="角色" width="180" prop="role_name">
        </el-table-column>
        <el-table-column label="状态" width="180" prop="mg_state">
          <!--作用域插槽 slot-scope
            slot-scope="scope" 接收作用域数据

              scope.row ：代表这行数据

              作用域插槽会覆盖prop，所以可以不写prop
              -->
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch v-model="scope.row.mg_state" @change="changestatus(scope.row)"> </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editDialogById(scope.row.id)"
             ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deluserById(scope.row.id)"
            ></el-button>
            <!-- 设置属性 enterable= false 鼠标离开，提示自动隐藏 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-start"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisiable"
      width="50%"
      @close="addDialogClose"
    >
      <el-form :model="addform" :rules="addformRules" ref="addformRef" label-width="80px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addform.username"></el-input>
          </el-form-item>
           <el-form-item label="用户密码" prop="password">
            <el-input v-model="addform.password"></el-input>
          </el-form-item>
           <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="addform.email"></el-input>
          </el-form-item>
           <el-form-item label="用户名称" prop="mobile">
            <el-input v-model="addform.mobile" prop="mobile"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button
        >
      </span>
    </el-dialog>


    <!--修改的对话框 -->
    
<el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form :model="editform" :rules="editformRules" ref="editformRef" label-width="80px">
          <el-form-item label="用户名称" >
            <el-input v-model="editform.username" disabled></el-input>
          </el-form-item>
  
           <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="editform.email"></el-input>
          </el-form-item>
           <el-form-item label="用户手机号" prop="mobile">
            <el-input v-model="editform.mobile" prop="mobile"></el-input>
          </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button
        >
      </span>
    </el-dialog>



  </div>
</template>
<script>
export default {
  data() {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,


      addDialogVisiable:false,


      // 添加表单数据
      addform:{
        username:'',
        password:'',
        email:'',
        mobile:'',
      },
      addformRules:{

        username:[
          { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password:[
           { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email:[
           { required: true, message: '请输入邮箱', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        mobile:[
           { required: true, message: '请输入手机号', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]

      },

      
      
      editDialogVisible :false,
      // 修改的表单数据
      editform:{

      },
      editformRules:{
       
        email:[
           { required: true, message: '请输入邮箱', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        mobile:[
           { required: true, message: '请输入手机号', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]

      }


    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      })

      if (res.meta.status != 200) return this.$message.error("")
      //  将数据保存到data中
      this.userlist = res.data.users
      this.total = res.data.total

      console.log(res)
    },

    //监听pageSize的改变
    handleSizeChange(newSize) {
      // console.log(newSize)
      ;(this.queryInfo.pagesize = newSize), this.getUserList()
    },

    // 监听页码值改变
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },

    // 当搜素框清空时触发
    clearquery() {
      this.getUserList()
    },

    //输入框值改变时触发
    changequery() {
      this.getUserList()
    },
    // 改变用户状态时回调函数
    async changestatus(userInfo){
    //  console.log(userInfo)   
      const {data:res} =  await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      console.log(res)
      if(res.meta.status !== 200){
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error("更新用户状态失败")
      }
      return this.$message.success("更新状态成功")
      
    },
     // 关闭添加用户对话框
    addDialogClose(){
      // 重置表单
     // console.log("关闭表单")
      this.$refs.addformRef.resetFields()
    },

    // 添加用户
    addUserInfo(){

      //1. 预校验表单数据
      this.$refs.addformRef.validate(async valid => {

          //校验失败，直接返回
          if(!valid) return 
          
            // 2.发起网络 添加用户
          const {data:res} = await  this.$http.post('users',this.addform)

  //   注意返回值成功状态吗为201
          if(res.meta.status !== 201){
            return this.$message.error("添加用户信息失败")
          }

          this.$message.success("添加成功")
          //关闭弹框
          this.addDialogVisiable = false
          // 更新列表
          this.getUserList()

      })

    

    },

    // 点击修改按钮 弹出对话框
   async  editDialogById(id){
// 弹出对话框
        this.editDialogVisible = true
//根据id查询对应数据
       const {data:res} = await  this.$http.get('users/'+id)

      //console.log(res)

      // 将获取的数据绑定
      this.editform =  res.data

    },
    //关闭修改对话框
    editDialogClose(){
      // 重置表单
      this.$refs.editformRef.resetFields()
    },
    //点击修改的确定
    editUserInfo(){

        // 1.预校验表单数据
        this.$refs.editformRef.validate(async valid =>{

            // console.log(valid)
            if(!valid) return

            // 连接网络进行修改
            const {data:res} = await this.$http.put('users/'+this.editform.id,{email:this.editform.email,mobile:this.editform.mobile})


            // console.log(res)
            if(res.meta.status !== 200) return this.$message.error("修改市表")

            // 修改成功
            this.$message.success("修改成功")

            // 关闭弹出框
            this.editDialogVisible = false

            // 刷新列表

            this.getUserList()

        })

    },
    //点击删除按钮
   async deluserById(id){

      // 弹框确认是否删除

      // 点击取消会有异常，所以catch(err)
     const info =  await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)

    // 点击确定 返回字符串confirm取消返回字符串 cancel
    // console.log(info)
       if(info == 'cancel') return  this.$message.error('已取消删除')

  // 联网删除
      const {data:res} =  await this.$http.delete('users/'+id)
      // console.log(res)
      if(res.meta.status !== 200) return  this.$message.error('删除失败')
      this.$message.success('删除成功')
      // 关闭弹框-- 自动关闭
      // 刷新列表
      this.getUserList()

    }


  }
 
}
</script>
<style lang="less" scoped>
</style>